import { defineComponent, ref, readonly, VNode, watch, Ref, onMounted } from 'vue'
/* http */
import * as IntellIgentApi from '@src/api/intelligentQuality.js'
/* utils */
import _ from 'lodash'
import state from '@src/modules/intelligentQuality/utils/state.ts'
/* scss */
import '@src/modules/intelligentQuality/views/newInfo/components/index.scss'
import { message } from '@src/util/message'


interface FieldQuality {
    enName: string,
    cnName: string,
}

interface actionForm {
    id: string,
    name: string,
    children?: actionForm[],
}

export default defineComponent({
    name: 'StepSettingField',
    props: {
        formId: {
            type: String,
            default: ''
        },
        fieldList: {
            type: Array,
            default: () => []
        },
        isEdit: {
            type: Boolean,
            default: false
        }
    },
    emits: ['change'],
    setup(props, { emit }) {
        const cascaderValue = ref<string[]>([]) // 执行应用选中状态值
        const checkFromId = ref('') // 当前选中的表单id
        const cascaderOptions = ref([]) // 执行应用选中配置信息
        const currentFormIdList = ref([]) // 当前表单的id 字段数据

        // 多级菜单配置信息数据
        const propsOpt = readonly({
            label: 'name',
            value: 'id',
            children: 'children',
        })

        // 对象字段
        const objFieldList = ref([
            {
                enName: '',
                cnName: '',
            }
        ]) as Ref<FieldQuality[]>
        
        /**
         * @description 选中多级菜单信息数据
         * @param value 
         */
        const handlerChange = (value: any) => {
            cascaderValue.value = value
            checkFromId.value = value[value.length - 1]
        }


        /**
         * @description 删除表单中如果数据children数据为空，则删除它
         * @param data 表单数据
         */
        const deleteChildrenHandler = (data: actionForm[]) => {
            data.forEach(item => {
                if (item.children) {
                    if (item.children.length == 0) {
                        delete item.children
                    } else {
                        deleteChildrenHandler(item.children);
                    }
                }
            });
        };


        // 找到表单父节点id并接成数组
        function findParentAndId(data: actionForm[], targetId: string): string[] {
            let result = [] as string[];
        
            function search(data: actionForm[], parentId: string | null = null): boolean {
                for (const item of data) {
                    if (item.id === targetId) {
                        result = parentId ? [parentId, item.id] : [item.id];
                        return true;
                    }
                    if (item.children && item.children.length > 0) {
                        if (search(item.children, item.id)) {
                            return true;
                        }
                    }
                }
                return false;
            }
        
            search(data);
            return result;
        }

        /**
         * @description 获取质检执行表单信息
         */
        const getActionList = async () => {
            try {
                const res = await IntellIgentApi.getIntelligentActionForm();

                if (!res.success) return;

                cascaderOptions.value = res.data;

                // 如果是编辑
                if (props.isEdit) {
                    const result = findParentAndId(cascaderOptions.value, props.formId);
                    cascaderValue.value = result;
                }

                deleteChildrenHandler(cascaderOptions.value);
            } catch (err) {
                console.log(err);
            }
        };

        /**
         * @description 根据表单id获取字段信息
         */
        const getFormField = (formId: string) => {
            IntellIgentApi.getIntelligentActionFormFields({ formId: formId })
                .then(res => {
                    if (!res.success) return
                    currentFormIdList.value = res.data
                })
                .catch(err => {
                    console.log(err)
                })
        }

        

        const handlerChangeObjField = (val: string, item: FieldQuality) => {
            item.enName = val
        }

        /**
         * @description 添加对象字段
         */
        const handlerAddObjField = () => {
            objFieldList.value.push({
                enName: '',
                cnName: '',
            })
        }

        /**
         * @description 删除对象字段
         */
        const handlerDeleteObjField = (val) => {
            if (objFieldList.value.length == 1) {
                message.warning("最少保留一个对象字段")
                return
            }
            objFieldList.value = objFieldList.value.filter(item => item !== val)
        }

        // 如果选中了checkFormId，则获取字段信息
        watch(() => checkFromId.value, (newValue, oldValue) => {
            if (newValue) {
                getFormField(checkFromId.value)
            }
        }, {immediate: true})

        // 编辑情况下,通过表单id来将字段信息赋值给objFieldList，以便多选框遍历
        watch(() => props.formId, (newValue, oldValue) => {
            if (newValue) {
                checkFromId.value = newValue
                if (props.isEdit) {
                    // 编辑状态下如果字段信息为空，则自动添加一个默认
                    if (props.fieldList.length === 0) {
                        objFieldList.value = [
                            {
                                enName: '',
                                cnName: '',
                            }
                        ]
                        return
                    }
                    objFieldList.value = props.fieldList.map(item => {
                        return {
                            enName: item.enName,
                            cnName: item.cnName,
                        }
                    })
                }
            }
        }, {immediate: true})

        watch([() => checkFromId.value, () => objFieldList.value], ([formIdNewVal,objFieldListNewVal], [oldVal,oldVal2]) => {
            // 如果表单id和对象字段都改变，则触发事件
            if (formIdNewVal && objFieldListNewVal.length !== 0) {
                emit('change', {
                    formId: formIdNewVal,
                    fieldList: objFieldListNewVal.map(item => {
                        return item.enName
                    }).filter(item => item)
                })
            }
        }, { deep: true, immediate: true })

        onMounted(() => {
            getActionList()
        })

        return () => (
            <div>
                <div class="cre-desc">
                    <div class="cre-desc-title">请选择需要机器人质检的目标字段</div>
                    <div class="cre-desc-info">选择需要质检的目标字段（目前系统仅可使用表单中“附件”类型的字段进行质检，且需要用户上传“图片”格式的附件才能触发该功能）</div>
                </div>
                <div class="cre-action-app">
                    <div class="cre-action-app-title">
                        {/* <em class={'cre-action-app-title-tip'}>*</em>  */}
                        执行应用
                        </div>
                    <div class="cre-action-cascader">
                        <el-cascader
                            value={cascaderValue.value}
                            options={cascaderOptions.value}
                            placeholder={'请选择应用'}
                            onChange={(val) => handlerChange(val)}
                            {
                                ...{
                                    props: {
                                        props: propsOpt
                                    }
                                }
                            }
                            style={{ width: '50%' }}
                        >
                        </el-cascader>
                    </div>
                </div>
                <div class="cre-obj-field">
                    <div class="cre-obj-field-title">对象字段</div>
                    <div class="cre-obj-field-list">
                        {
                            objFieldList.value.map(item => {
                                return (
                                    <div class="cre-obj-field-item" style={{ width: 'calc(50% + 32px)' }}>
                                        <div class="cre-obj-field-ipt">
                                            <el-select placeholder="请选择对象字段" value={item.enName} onChange={(val) => handlerChangeObjField(val, item)} style={{ width: '100%' }}>
                                                {
                                                    currentFormIdList.value.length !== 0 && currentFormIdList.value.map(item => {
                                                        return (
                                                            <el-option
                                                                label={item.cnName}
                                                                value={item.enName}
                                                            >
                                                            </el-option>
                                                        )
                                                    })
                                                }
                                            </el-select>
                                        </div>
                                        <div class="cre-obj-field-delete iconfont icon-delete" onClick={() => handlerDeleteObjField(item)}></div>
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div class="cre-obj-field-add" onClick={() => handlerAddObjField()}>
                        {/* 临时先干掉 */}
                        {/* <el-button type="plain-third">
                            <i class="iconfont icon-add2"></i>
                                添加质检字段
                            </el-button> */}
                    </div>
                </div>
            </div>
        )
    }
})